/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package cn.ac.iie.di.ban.tools;

import cn.ac.iie.di.ban.commons.RuntimeEnv;
import com.alibaba.fastjson.JSON;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;

/**
 *
 * @author xiaoliang
 */
public class DataBuffer {

    private static Logger logger = Logger.getLogger(DataBuffer.class.getName());
    public static ConcurrentMap<String, String> reqUidMap = new ConcurrentHashMap<>();
    public static ConcurrentMap<String, Map<String, Object>> channelIdMap = new ConcurrentHashMap<>();
    public static ConcurrentMap<String, Map<String, Object>> agencyMap = new ConcurrentHashMap<>();
    
    public static HttpPostHelper metaFind = new HttpPostHelper(RuntimeEnv.getParamAsString(RuntimeEnv.METADATAURL));
    public static HttpPostHelper agencyFind = new HttpPostHelper(RuntimeEnv.getParamAsString(RuntimeEnv.AGENCYURL));
//    public void putReqUid(Map<String, String> reqUidOne) {
//        reqUidMap.putAll(reqUidOne);
//    }

    public static String getUid(String req_id) {
        String uid = reqUidMap.get(req_id);
        if (uid == null) {
            String ruid = getUid4meta(req_id);
            if (!"".equals(ruid)) {
                reqUidMap.put(req_id, ruid);
            }
            return ruid;
        }
        return uid;
    }

    public static Map<String, Object> getId4Channel(String uid, String opinion_field, String source_tunnel, String source_type) {
        String key = uid + opinion_field + source_tunnel + source_type;
        Map<String, Object> channelId = channelIdMap.get(key);
        if (channelId == null) {
            Map<String, Object> rchannelId = findAgency(uid, opinion_field, source_tunnel, source_type);
            if (rchannelId != null) {
                channelIdMap.put(key, rchannelId);
                return rchannelId;
            }
            return new HashMap<>(1);
        }
        return channelId;
    }
    
    public static Map<String,Object> getAgencyAllbyUid(String uid){
        Map<String,Object> agencys = agencyMap.get(uid);
        if(agencys == null){
            Map<String,Object> agencyAll = findAgencyByUid(uid);
            if(agencyAll!=null){
                agencyMap.put(uid, agencyAll);
                return agencyAll;
            }
            return new HashMap<>(1);
        }
        return agencys;
    }

    /*
      request 中查询 根据req_id查uid
     */
    public static String getUid4meta(String req_id) {
        try {
            Map<String, String> findReqId = new HashMap<>();
            findReqId.put("scope", "request");
            findReqId.put("opration", "search");
            //where
            Map<String, String> condition = new HashMap<>();
            condition.put("req_id", req_id);
            JSONObject conditionJSON = JSONObject.fromObject(condition);
            findReqId.put("condition", conditionJSON.toString());
            //result msg
            Map<String, String> content = new HashMap<>();
            content.put("uid", "");
            JSONObject contentJSON = JSONObject.fromObject(content);
            findReqId.put("content", contentJSON.toString());
            List<Map<String, Object>> datas;
            synchronized (metaFind) {
                String result = metaFind.postMsg(findReqId);
                Map<String, Object> resultMap = JSON.parseObject(result);
                datas = ((List<Map<String, Object>>) resultMap.get("data"));
            }
            if (datas != null) {
                return datas.get(0).get("uid").toString();
            }
            return "";
        } catch (IOException e) {
            logger.info(e.getMessage(), e);
            return "";
        }
    }
    
    public static Map<String, Object> findAgencyByUid(String uid) {
        try {
            Map<String, String> findMap = new HashMap<>();
            findMap.put("uid", uid);
            findMap.put("opinion_field", "-1");
            findMap.put("source_tunnel", "-1");
            findMap.put("source_type", "-1");
            Map<String, Object> resultMap;
            synchronized (agencyFind) {
                String result = agencyFind.postMsg(findMap);
                resultMap = JSON.parseObject(result);
            }
            if (resultMap != null && !"fail".equals(resultMap.get("status"))) {
                logger.debug(resultMap.toString());
                return (Map<String, Object>) resultMap.get("result");
            }
            return null;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    public static Map<String, Object> findAgency(String uid, String opinion, String source_tunnel, String source_type) {
        try {
            Map<String, String> findMap = new HashMap<>();
            findMap.put("uid", uid);
            findMap.put("opinion_field", opinion);
            findMap.put("source_tunnel", source_tunnel);
            findMap.put("source_type", source_type);
            Map<String, Object> resultMap;
            synchronized (agencyFind) {
                String result = agencyFind.postMsg(findMap);
                resultMap = JSON.parseObject(result);
            }
            if (resultMap != null && !"fail".equals(resultMap.get("status"))) {
                logger.debug(resultMap.toString());
                return (Map<String, Object>) resultMap.get("result");
            }
            return null;
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
        return null;
    }

    /*
    查找元数据中task 表中的req_id 
     */
    public static String[] findReqId(String task_id) {
        try {
            Map<String, String> findReqId = new HashMap<>();
            findReqId.put("scope", "task");
            findReqId.put("opration", "search");
            //where
            Map<String, String> condition = new HashMap<>();
            condition.put("task_id", task_id);
            JSONObject conditionJSON = JSONObject.fromObject(condition);
            findReqId.put("condition", conditionJSON.toString());
            //result msg
            Map<String, String> content = new HashMap<>();
            content.put("req_id", "");
            JSONObject contentJSON = JSONObject.fromObject(content);
            findReqId.put("content", contentJSON.toString());
            List<Map<String, Object>> datas;
            synchronized (metaFind) {
                String result = metaFind.postMsg(findReqId);
                Map<String, Object> resultMap = JSON.parseObject(result);
                datas = ((List<Map<String, Object>>) resultMap.get("data"));
            }
            if(datas != null){
                return datas.get(0).get("req_id").toString().split("[,]");
            }
            return new String[0];
        } catch (IOException e) {
            logger.info(e.getMessage(), e);
        }
        return new String[0];
    }
}
